<?php
require 'include/utils/str_util.php';

class WebDispatcher{
    static function create(){
        global $config;
        // 获取请求路径
        $target = $_SERVER['PHP_SELF'];
        $position = strpos($target, $config["HOST_NAME"]);
        $full_route = substr($target, $position + strlen($config["HOST_NAME"]));
        $file_target = '';
        if(empty($full_route)){
            $file_target = 'index';
        }
        // 获取 controller 文件
        $file_parse_list = parse_url_without_header($full_route);
        $file_target = $file_parse_list["parent"];
        $left_route = $file_parse_list["left"];
        if(empty($file_target)){
            $file_target = 'index';
        }
        $filename = 'controller/'.$file_target.'.controller.php';
        if(file_exists($filename)){
            try{
                require $filename;
                // 获取请求方法名
                $targetClass = $file_target.'_controller';
                $targetObj = new $targetClass();
                $method_target = '';
                if(empty($left_route)){
                    $method_target = 'index';
                }else{
                    $method_parse_list = parse_url_without_header($left_route);
                    $method_target = $method_parse_list["parent"];
                    $left_route = $method_parse_list["left"];
                }
                if(method_exists($targetObj, $method_target)){
                    // 模型自动装配
                    $db = new Model($file_target);
                    $model = $db->model;
                    $targetObj -> $method_target($model);
                }else{
                    header("Content-Type: text/html");
                    echo "<span style='color:#666;padding:30px 0;display:inline-block;width:100%;font-size:40px;font-weight:bold; text-align:center;'>404 - 页面未找到</span>";
                }
            }catch(Exception $e){
                echo Json::Fail(1, $e->getMessage(), null);
            }
        }else{
            header("Content-Type: text/html");
            echo "<span style='color:#666;padding:30px 0;display:inline-block;width:100%;font-size:40px;font-weight:bold; text-align:center;'>404 - 页面未找到</span>";
        }
        
    }
}